/* eslint-disable no-async-promise-executor */
import { HotSearch, Book } from '../models';

export default function (router) {
  /**
   * 前端接口
   * 首页获取栏目数据的接口
   */
  router.get('/api/front/hot-search', async ctx => {
    const list = await HotSearch.find()
      .sort({ priority: 1, create_time: 1 })
      .populate({
        path: 'book',
        options: {
          select: 'name author img_url des classify create_time'
        }
      });
    await ctx.json(true, '获取热门搜索书籍成功', { list });
  });

  /**
   * 后台接口
   * 列出所有的热门搜索书籍
   */
  router.get('/api/admin/hot-search', async ctx => {
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const list = await HotSearch.find()
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ priority: 1, create_time: 1 })
      .populate({
        path: 'book',
        options: {
          select: 'name author img_url des classify create_time'
        }
      });
    const total = await HotSearch.countDocuments();
    await ctx.json(true, '获取热门搜索书籍成功', { list, total });
  });

  /**
   * 后台接口
   * 新增热门搜索书籍
   */
  router.post('/api/admin/hot-search', async ctx => {
    const { books } = ctx.request.body;
    const thisHotSearch = await HotSearch.findOne({ book: { $in: books } });
    const maxPriority = await HotSearch.countDocuments();
    if (thisHotSearch) {
      await ctx.json(false, '该书籍已存在');
      return false;
    }
    if (maxPriority >= 10) {
      await ctx.json(false, '最多可设置10本书');
      return false;
    }
    for (let i = 0; i < books.length; i++) {
      const thisBook = await Book.findById(books[i], '_id des');
      if (thisBook) {
        const current = await HotSearch.countDocuments();
        await HotSearch.create({
          // @ts-ignore
          priority: current + 1,
          book: await ctx.transId(books[i]),
          recommend_text: thisBook.des.substring(0, 20),
          create_time: new Date()
        });
      }
    }
    await ctx.json(true, '新增热门搜索书籍成功');
  });

  /**
   * 后台接口
   * 修改热门搜索书籍
   */
  router.put('/api/admin/hot-search/:id', async ctx => {
    const { id } = ctx.params;
    const result = await HotSearch.updateOne(
      { _id: id },
      {
        $set: ctx.request.body
      }
    );
    if (result.ok === 1) {
      const newest = await HotSearch.findById(id);
      await ctx.json(true, '更新热门搜索书籍成功', newest);
    } else {
      await ctx.json(true, '更新热门搜索书籍失败', result);
    }
  });

  /**
   * 后台接口
   * 删除热门搜索书籍
   */
  router.delete('/api/admin/hot-search/:id', async ctx => {
    const { id } = ctx.params;
    const thisData = await HotSearch.findOne({ _id: id }, 'priority');
    if (!thisData) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const operation = await HotSearch.deleteOne({ _id: id });
    // 更新顺序
    const update = await HotSearch.updateMany({ priority: { $gt: thisData ? thisData.priority : 100000 } }, { $inc: { priority: -1 } });
    if (operation.ok && update.ok) {
      await ctx.json(true, '删除热门搜索书籍成功');
    } else {
      await ctx.json(false, '删除热门搜索书籍失败');
    }
  });

  /**
   * 后端接口
   * 交换热门搜索书籍位置
   */
  router.post('/api/admin/hot-search/exchange', async ctx => {
    const { from: fromIndex, to: toIndex, book } = ctx.request.body;
    if (!fromIndex || !toIndex) await ctx.json(false, '参数错误');
    if (fromIndex === toIndex) await ctx.json(false, '交换顺序不能相同');

    let updateCur, updateOther;
    if (fromIndex > toIndex) {
      updateOther = await HotSearch.updateMany({ priority: { $lt: fromIndex, $gte: toIndex } }, { $inc: { priority: 1 } });
      updateCur = await HotSearch.updateOne({ book }, { $set: { priority: toIndex } });
    } else {
      updateOther = await HotSearch.updateMany({ priority: { $gt: fromIndex, $lte: toIndex } }, { $inc: { priority: -1 } });
      updateCur = await HotSearch.updateOne({ book }, { $set: { priority: toIndex } });
    }

    if (updateCur.ok && updateOther.ok) {
      await ctx.json(true, '交换成功');
    } else {
      await ctx.json(false, '交换失败');
    }
  });
}
